package com.haoshuang.zhouzhoubang.ui.page.mine.settings

import android.content.Context
import android.graphics.Color
import android.os.Bundle
import com.azhon.appupdate.manager.DownloadManager
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.AppUtils
import com.haoshuang.zhouzhoubang.R
import com.haoshuang.zhouzhoubang.config.URLConstants
import com.haoshuang.zhouzhoubang.databinding.ActivitySettingsBinding
import com.haoshuang.zhouzhoubang.model.event.LogoutEvent
import com.haoshuang.zhouzhoubang.ui.activity.AddressManagementActivity
import com.haoshuang.zhouzhoubang.ui.activity.BindWeChatNoticeActivity
import com.haoshuang.zhouzhoubang.ui.activity.ChangePhoneNumberActivity
import com.haoshuang.zhouzhoubang.ui.activity.LoginPasswordActivity
import com.haoshuang.zhouzhoubang.ui.activity.NoticeSettingsActivity
import com.haoshuang.zhouzhoubang.ui.activity.SetEmergencyContactActivity
import com.haoshuang.zhouzhoubang.ui.dialog.ConfirmDialog
import com.haoshuang.zhouzhoubang.ui.dialog.Tis2Dialog
import com.haoshuang.zhouzhoubang.ui.page.account.login.LoginActivity
import com.haoshuang.zhouzhoubang.ui.page.help.detail.HelpDetailActivity
import com.jeremyliao.liveeventbus.LiveEventBus
import com.lnkj.jialubao.utils.AccountUtils
import com.lxj.xpopup.XPopup
import com.mufeng.libs.base.BaseVMActivity
import com.mufeng.libs.state.observeState
import com.mufeng.libs.utils.CacheUtil
import com.mufeng.libs.utils.browse
import com.mufeng.libs.utils.callPhone
import com.mufeng.libs.utils.startPage
import com.mufeng.libs.utils.startPageForResult
import com.mufeng.libs.utils.toast
import com.mufeng.libs.utils.view.click
import com.mufeng.libs.utils.view.clickWithTrigger


/**
 *  设置
 */
class SettingsActivity : BaseVMActivity<SettingsViewModel, ActivitySettingsBinding>() {

    companion object {
        fun launch(context: Context) {
            context.startPage<SettingsActivity>()
        }
    }

    override fun initView(savedInstanceState: Bundle?) {

        binding.titleBar.title = "设置"
        binding.titleBar.leftImageView().click { finish() }

        binding.apply {
            // 获取版本信息
            ceVersion.setTitle("当前版本 (${AppUtils.getAppVersionName()})")
            ceVersion.clickWithTrigger {
                // 点击获取版本信息
                vm.getAppVersions()
            }

            tvAddressManager.clickWithTrigger {
                startPage<AddressManagementActivity>("type" to 0)
            }

            // 手机通知设置
            ceNotice.clickWithTrigger {
                // 点击手机通知设置
                startPage<NoticeSettingsActivity>()
            }

            // 微信订阅
            ceWeChat.clickWithTrigger {
                // 点击微信订阅
                startPage<BindWeChatNoticeActivity>()
            }

            // 短信通知
            ivSmsOpen.isSelected = AccountUtils.user?.is_note == 1
            ivSmsClose.isSelected = AccountUtils.user?.is_note == 0
            llSmsOpen.click {
                if (ivSmsOpen.isSelected) return@click
                vm.setNote(1)
            }
            llSmsClose.click {
                // 点击短信通知
                if (ivSmsClose.isSelected) return@click
                vm.setNote(0)
            }

            // 登录密码修改
            tvSetLoginPassword.clickWithTrigger {
                // 点击登录密码修改
                startPage<LoginPasswordActivity>()
            }

            // 手机号修改
            tvSetPhoneNumber.setText(AccountUtils.user?.phone ?: "")
            tvSetPhoneNumber.clickWithTrigger {
                // 点击手机号修改
                startPageForResult<ChangePhoneNumberActivity> { code, data ->
                    if (code == 200) {
                        tvSetPhoneNumber.setText(AccountUtils.user?.phone ?: "")
                    }
                }
            }

            // 客户经理
            tvAccountManager.clickWithTrigger {
                val phone = AccountUtils.user?.team?.service_phone ?: ""
                val name = AccountUtils.user?.team?.service_name ?: ""
                if (phone.isEmpty()) {
                    toast("您还没有专属客户经理, 请联系客服")
                    return@clickWithTrigger
                }
                XPopup.Builder(mActivity)
                    .asCustom(
                        ConfirmDialog(
                            context = mActivity,
                            title = "专属客户经理",
                            content = "$name: $phone",
                            cancelStr = "取消",
                            confirmStr = "拨打电话",
                            isHideCancel = false,
                            onCancel = {},
                            onConfirm = {
                                callPhone(AccountUtils.user?.team?.service_phone ?: "")
                            })
                    )
                    .show()
            }

            // 备用手机号修改
            tvSparePhone.setText(AccountUtils.user?.spare_phone ?: "")
            tvSparePhone.clickWithTrigger {
                // 点击备用手机号修改
                startPageForResult<SetEmergencyContactActivity> { code, data ->
                    if (code == 200) {
                        tvSparePhone.setText(AccountUtils.user?.spare_phone ?: "")
                    }
                }
            }

            // 缓存清理
            tvCache.setText(CacheUtil.getTotalCacheSize(mActivity))
            tvCache.setValueColor(R.color.c_99)
            tvCache.clickWithTrigger {
                // 点击缓存清理
                XPopup.Builder(mActivity)
                    .asCustom(
                        ConfirmDialog(
                            context = mActivity,
                            title = "缓存清理",
                            content = "确定要清理缓存吗？",
                            cancelStr = "取消",
                            confirmStr = "确认",
                            isHideCancel = false,
                            onCancel = {},
                            onConfirm = {
                                CacheUtil.clearAllCache(mActivity)
                                toast("清理成功")
                                tvCache.setText("0KB")
                            })
                    )
                    .show()
            }

            // 隐私政策
            tvYs.clickWithTrigger {
                // 点击隐私政策
                startPage<HelpDetailActivity>(
                    "title" to "隐私政策",
                    "url" to URLConstants.privacyPolicy
                )
            }

            // 注销
            tvZx.clickWithTrigger {
                XPopup.Builder(mActivity)
                    .asCustom(
                        Tis2Dialog(
                            mActivity,
                            "确定要注销账号吗,注销账号后服务数据将无法恢复"
                        ) {
                            vm.getData6()
                        }).show()
            }

            // 退出登录
            loginOut.clickWithTrigger {
                XPopup.Builder(mActivity)
                    .asCustom(
                        ConfirmDialog(
                            context = mActivity,
                            title = "温馨提示",
                            content = "确定要退出登录吗?",
                            cancelStr = "取消",
                            confirmStr = "确定",
                            isHideCancel = false,
                            onCancel = {},
                            onConfirm = {
                                AccountUtils.logout()
                                LiveEventBus.get(LogoutEvent::class.java).post(LogoutEvent)
                                startPage<LoginActivity>()
                                ActivityUtils.finishOtherActivities(LoginActivity::class.java)
                            })
                    )
                    .show()
            }
        }


    }

    override fun initData() {

    }

    override fun startObserve() {
        vm.getAppVersionsData.observeState(this) {
            onSuccess {
                if (it != null) {
                    val manager = DownloadManager.Builder(mActivity).run {
                        apkUrl(it.android_download_url!!)
                        apkName("zhouzhoubang.apk")
                        smallIcon(R.mipmap.logo)
                        showNewerToast(true)
                        apkVersionCode(it.versions_code!!)
                        apkVersionName("V ${it.versions_no}")
                        apkDescription(it.content!!)
                        enableLog(true)
                        jumpInstallPage(true)
                        dialogButtonTextColor(Color.WHITE)
                        showNotification(true)
                        showBgdToast(true)
                        forcedUpgrade(it.is_force == 1)
                        build()
                    }
                    manager.download()
                }
            }
        }
        vm.getData6.observeState(this) {
            onLoading { showLoading() }
            onError { code, msg ->
                dismissLoading()
                toast(msg)
            }
            onSuccess {
                dismissLoading()
                toast("注销成功")
                AccountUtils.logout()
                LiveEventBus.get(LogoutEvent::class.java).post(LogoutEvent)
                startPage<LoginActivity>()
            }
        }

        vm.setNoteData.observeState(this) {
            onLoading { showLoading() }
            onError { code, msg ->
                dismissLoading()
                toast(msg)
            }
            onSuccess {
                dismissLoading()
                val user = AccountUtils.user
                if (user?.is_note == 1) {
                    user.is_note = 0
                    binding.ivSmsClose.isSelected = true
                    binding.ivSmsOpen.isSelected = false
                } else {
                    user?.is_note = 1
                    binding.ivSmsClose.isSelected = false
                    binding.ivSmsOpen.isSelected = true
                }
                AccountUtils.user = user
            }
        }
    }

}